﻿using Microsoft.AspNetCore.Mvc;
using Mojito.Model;
using Mojito.Services;
using Mojito.Utils;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace Mojito.Controllers
{
    [Route("api/request")]
    public class RequestController : ControllerBase
    {
        public RequestService _RequestService { get; set; }

        /// <summary>
        ///  载入环境
        /// </summary>
        /// <returns></returns>
        [HttpGet("enviroment/{workDirId}")]
        public async Task<IActionResult> GetEnvironment()
        {
            return Ok();
        }

        /// <summary>
        ///  载入请求
        /// </summary>
        /// <param name="Id">请求id</param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        public async Task<IActionResult> Get(string Id)
        {
            var request = await _RequestService.Get(Id);
            var requestExmaple = await _RequestService.GetExample(Id);
            if (request == null)
                throw new ApplicationException("找不到该对象");
            var output = new RequestDto
            {
                Id = request.Id,
                Title = request.Title,
                Status = 0,
                Description = request.Description,
                Url = request.RequestUrl,
                FolderId = request.FolderId,
                Body = request.Body,
                Method = request.Method,
                ExampleId = requestExmaple.Id,
                RequestExample = new RequestDto.Example
                {
                    Text = requestExmaple.RequestText,
                    Json = new object[0]
                },
                ResponseExample = new RequestDto.Example
                {
                    Text = requestExmaple.ResponseText,
                    Json = new object[0]
                }
            };
            output.Header = output.SetHeader(request.Header);
            return Success(data: output);
        }

        /// <summary>
        ///  保存请求
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] RequestDto input)
        {
            var output = await _RequestService.Save(input);
            return Success(data: output);
        }
        
        /// <summary>
        ///  删除请求
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpDelete("{Id}")]
        public async Task<IActionResult> DestroyRequest(string Id)
        {
            var output = await _RequestService.Destroy(Id);
            return Success(data: output);
        }

        /// <summary>
        ///  发送请求
        /// </summary>
        /// <param name="input"></param>
        [HttpPost("do")]
        public async Task<IActionResult> doRequest([FromBody] DoRequestInput input)
        {
            var url = _RequestService.Replace(input.Url, input.EnviromentId);
            var body = _RequestService.Replace(input.Body, input.EnviromentId);

            var headerDir = new Dictionary<string, string>();
            foreach(var head in input.Header)
            {
                if(!string.IsNullOrWhiteSpace(head.Key) || !string.IsNullOrWhiteSpace(head.Value))
                    headerDir.Add(head.Key, head.Value);
            }

            var response = new HttpResponseMessage();
            switch (input.Method)
            {
                case Data.Enums.RequestMethod.GET:
                    response = await HttpUtil.GetAsync(url, headerDir);
                    break;
                case Data.Enums.RequestMethod.POST:
                    response = await HttpUtil.PostAsync(url, body, headerDir);
                    break;
            }
            var output = new DoRequestOutput()
            {
                StatusCode = response.StatusCode,
                StatusText = response.ReasonPhrase,
                Header = new List<HeaderDto>(),
                Body = await response.Content.ReadAsStringAsync()
            };

            foreach (var h in response.Content.Headers)
            {
                output.Header.Add(new HeaderDto
                {
                    Key = h.Key,
                    Value = string.Join(';', h.Value)
                });
            }
            foreach (var h in response.Headers)
            {
                output.Header.Add(new HeaderDto
                {
                    Key = h.Key,
                    Value = string.Join(';', h.Value)
                });
            }
          
            return Success(data: output);
        }
    }
}
